<?php
namespace control;
/*
*物资档案类
*/

class resourceClass extends adIndexClass
{
	private const page  = 'resource';
	private const table = 'resource';
	private const title = '物资档案';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'      => [
                        'name'  => "{l.resource.homeSearch.type}",
                        'width' => 200,
                    ],
                    'code' => [
                        'name'  => "{l.resource.homeSearch.code}",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "{l.resource.homeSearch.name}",
                        'width' => 200,
                    ],
                    'model'         => [
                        'name'  => '{l.resource.homeSearch.model}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '{l.resource.homeSearch.unit}',
                        'width' => 100,
                    ],
                    'stockNum'    => [
                        'name'  => '{l.resource.homeSearch.stockNum}',
                        'width' => 150,
                    ],
                    'price'    => [
                        'name'  => '{l.resource.homeSearch.price}（' . static::$unit . '）',
                        'width' => 150,
                    ],
                    'money'    => [
                        'name'  => '{l.resource.homeSearch.money}（' . static::$unit . '）',
                        'width' => 150,
                    ],
                    'state'    => [
                        'name'  => '{l.resource.homeSearch.state}',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L("resource.home.code") => text(array("name" => "code")),
                    L("resource.home.name")     => text(array("name" => "name")),
                    L("resource.home.type") => select(array("name" => "type", "option" => explode('，', para('resourceType')))),
                ],
                [
                    L("resource.home.model")     => text(array("name" => "model")),
                    L("resource.home.state") => select(["name" => "state", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('resource.homeSearch.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('resource.homeSearch.del') . "</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>" . L('resource.homeSearch.start') . "</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>" . L('resource.homeSearch.stop') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
		//返回
		return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"code"  => $this->post('code'),//编码
			"name"  => $this->post('name'),//品名
			"model" => $this->post('model'),//规格
		);
		//全等查询数组
		$equal = array(
			"state" => $this->post('state'),//状态
			"type"  => $this->post('type'),//类型
		);
		//排序
		$orderBy = $this->listSort(array(
			"search"  => $this->post('list_sort_key') ?: 'time',
			"sort" => $this->post('list_sort') ?: "desc",
			"array"   => array(),
		));
		//获取查询结果
		$where                       = search(array("like" => $like, "=" => $equal));
		$page                        = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"edit"   => array("title" => L('resource.homeSearch.edit'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
				"detail" => array("title" => L('resource.homeSearch.detail'), "click" => "newIframe('" . L('resource.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            $stockNum = find(array('table' => 'stock_record', 'single' => " materialId = '$array[id]'", 'sum' => "num"));
            $total    = find(array('table' => 'stock_record', 'single' => " materialId = '$array[id]' and type = '入库单'", 'field' => " ifnull(sum(price*num),0) as money,ifnull(sum(num),0) as num"));
            $price    = $total['num'] > 0 ? self::formattingFigure($total['money'] / $total['num'], 'pricePrecision') : 0;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stockNum":
                        $row[] = self::lostZero($stockNum, 'numPrecision');
                        break;
                    case "price":
                        $row[] = $price;
                        break;
                    case "money":
                        $row[] = self::formattingFigure($stockNum * $price, 'amount');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        $numTotal = find(array("table" => 'stock_record',"sum" => "num","where" => " type = '入库单' "));
        $moneyAll = ['total'=>0];
		if($numTotal > 0) {
            $moneyAll = find(array("table" => self::table, "field" => " ifnull(sum(round(((select ifnull(sum(price*num),0) from stock_record where materialId = resource.id and type = '入库单')/(select ifnull(sum(num),0) from stock_record where materialId = resource.id and type = '入库单')*(select ifnull(sum(num),0) from stock_record where materialId = resource.id)),2)),0) as total ", "single" => $where));
        }
        $total = [
            'money' => $moneyAll['total'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total" => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 下载模板
	 */
	public function downloadModel()
	{
        $templateId = $this->get('templateId');
		if (!$this->power(self::page, 'edit')) {
			$_SESSION['warn'] = L('resource.downloadModel.power');
        }  else {
            $exampleData[] = ['打印纸', '办公用品', 'A4', '件', '20', '样例数据，导入时请删除本条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '品名'=>$example[0],
                            '类型'=>$example[1],
                            '规格'=>$example[2],
                            '计量单位'=>$example[3],
                            '参考单价'=>$example[4],
                            '备注'=>$example[5],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
			$text   = str_replace(['{{staffName}}'], [$this->control['name']], L('resource.downloadModel.log'));
			$this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/*数据导入分析*/
	public function importData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = L('resource.importData.power');
        } else {
			 $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list=0;
			foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
					$field         = array(
						"id"         => self::getId(),
						'stid'       => $this->control['stid'],
						'name'       => $cell['品名'],
						'type'       => $cell['类型'],
						'text'       => $cell['备注'],
						'unit'       => $cell['计量单位'],
						'model'      => $cell['规格'],
						'price'      => $cell['参考单价'] ? self::formattingFigure((float)$cell['参考单价'], 'pricePrecision') : 0,
						'state'      => '启用',
						'updateTime' => $this->time,
						"time"       => date("Y-m-d H:i:s"),
					);
					$userNo        = codeTemplateClass::generateCode(self::page, [
						'prefix' => 'QS',
						'table'  => self::table,
						'field'  => 'code',
						'where'  => '',
					], $field);
					$field['code'] = $userNo;
					$annotation    = [
						'name'  => L('resource.homeSearch.name'),
						'type'  => L('resource.homeSearch.type'),
						'model' => L('resource.homeSearch.model'),
						'unit'  => L('resource.homeSearch.unit'),
					];
					$rules         = [
						'name'  => 'required',
						'type'  => 'required',
						'model' => 'required',
						'unit'  => 'required',
					];
					// 校验是否符合规则
					$vt     = new \verify();
					$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
					if ($result === false) {
						$text .= str_replace(['{{i}}'], [$row_list], L('resource.importData.row')) . $vt->getErrs()[0] . "\n";  // 多个规则提示最前面一条
					} else {
						$warn = insert(["table" => self::table, "field" => $field]);
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$x++;
							$text .= "第【" . $row_list . "】行导入成功\n";
						} else {
                            $text .= "第【" . $row_list . "】行导入失败：数据库操作失败\n";
						}
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$text = str_replace(['{{staffName}}','{{fileName}}'], [$this->control['name'],$_FILES['file']['name']], L('resource.importData.log')) . $text;
			$this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}


	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = L('resource.exportData.power');
        }  else {
			$data   = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "st.stid in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '编码'=>$array['code'],
                            '品名'=>$array['name'],
                            '类型'=>$array['type'],
                            '规格'=>$array['model'],
                            '计量单位'=>$array['unit'],
                            '参考单价'=>self::lostZero($array['price'], 'pricePrecision'),
                            '状态'=> $array['state'],
                            '备注'=>$array['text'],
                            '创建人'=>self::findStaff($array['stid']),
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('resource.exportData.log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, L('resource.exportData.fileName').".xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id   = $this->post('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('resource.homeSearch.name')."：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    must . L('resource.homeSearch.type')."：" => select(["name" => "type", 'title' => L('resource.homeSearch.type'), 'option' => explode('，', para('resourceType')), "value" => $info['type']]),
                ],
                [
                    must . L('resource.homeSearch.model')."：" => text(["name" => "model", 'class' => 'text', "value" => $info['model']]),
                    must . L('resource.homeSearch.unit')."：" => select(["name" => "unit", 'title' => L('resource.homeSearch.unit'), 'option' => explode('，', para('resourceUnit')), "value" => $info['unit']]),
                ],
                [
                    L('resource.homeSearch.referencePrice')."：" => text(["name" => "price", 'unit' =>  static::$unit , 'class' => 'text', 'other' => self::digitalFiltering('pricePrecision'), "value" => $info['price'] ? self::lostZero($info['price'], 'pricePrecision') : '']),
                ],
                [
                    L('resource.homeSearch.remark')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

	public function editEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'name'       => $this->post('name'),
			'type'       => $this->post('type'),
			'text'       => $this->post('text'),
			'unit'       => $this->post('unit'),
			'model'      => $this->post('model'),
			'price'      => $this->post('price') ? self::formattingFigure($this->post('price'), 'numPrecision') : 0,
			'updateTime' => $this->time,
		];
		$annotation = [
			'name'  => L('resource.homeSearch.name'),
			'type'  => L('resource.homeSearch.type'),
			'model' => L('resource.homeSearch.model'),
			'unit'  => L('resource.homeSearch.unit'),
		];
		$rules      = [
			'name'  => 'required',
			'type'  => 'required',
			'model' => 'required',
			'unit'  => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('resource.editEdit.power');
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'QS',
					'table'  => self::table,
					'field'  => 'code',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'    => $id,
					'code'  => $userNo,
					'stid'  => $this->control['stid'],
					'state' => '启用',
					'time'  => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('resource.editEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('resource.detail.empty');
		} else {
			//菜单
			$data = array(
				"id"    => $info['id'],
				"title" => L('resource.detail.detail'),
			);
			//库存
			$stockNum = find(array('table' => 'stock_record', 'single' => " materialId = '$info[id]'", 'sum' => "num"));
			$total    = find(array('table' => 'stock_record', 'single' => " materialId = '$info[id]' and type = '入库单'", 'field' => " ifnull(sum(price*num),0) as money,ifnull(sum(num),0) as num"));
			$price    = $total['num'] > 0 ? self::formattingFigure($total['money'] / $total['num'], 'pricePrecision') : 0;
			$button   = [];
			if ($this->power(self::page, "edit")) {
				//按钮
				$button[] = [
					"name"  => L('resource.homeSearch.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
				//按钮
				$button[] = [
					"name" => L('resource.homeSearch.del'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				"详细信息" => array(
					array(
                        L('resource.homeSearch.name') => $info['name'],
                        L('resource.homeSearch.type') => $info['type'],
                        L('resource.homeSearch.model') => $info['model'],
                        L('resource.homeSearch.unit')   => $info['unit'],
					),
					array(
                        L('resource.homeSearch.referencePrice')."(" . static::$unit . ")" => $info['price'],
                        L('resource.homeSearch.stockNum') => self::lostZero($stockNum, 'numPrecision'),
                        L('resource.homeSearch.price') => $price,
                        L('resource.homeSearch.money') => self::lostZero($stockNum * $price, 'amount'),
					),
					array(
                        L('resource.homeSearch.remark') => pre($info['text']),
					),
				),
                L('resource.homeSearch.sys') => array(
					array(
                        L('resource.homeSearch.code')     => $info['code'],
                        L('resource.homeSearch.stid')   => self::findStaff($info['stid']),
                        L('resource.homeSearch.time') => $info['time'],
                        L('resource.homeSearch.updateTime') => $info['updateTime'],
					),
					array(
                        L('resource.homeSearch.state')     => $info['state'],
					),
				),
			));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitch()
	{
		$type = $this->post('type');
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
                    L('resource.stateSwitch.tips')."：" => str_replace(['{{type}}'], [$type], L('resource.stateSwitch.tipsWord')),
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $type)),
		));
		//返回
		return $this->layer(array("title" => L('resource.stateSwitch.stateSwitch'), "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit()
	{
		$idArr = $this->post('listId');
		$state = $this->post('type');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('resource.stateSwitchEdit.power');
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = L('resource.stateSwitchEdit.noChoice');
		} elseif (!in_array($state, ['启用', '停用'])) {
			$json['warn'] = L('resource.stateSwitchEdit.typeError');
		} else {
			$field        = [
				'state' => $state,
			];
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}','{{type}}','{{state}}','{{idArr}}'], [$this->control['name'],$type,$state,$idArr], L('resource.stateSwitchEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = L('resource.operate.del');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}','{{idArr}}'], [$msg], L('resource.operate.warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('resource.delete.power');
		} elseif (empty($array)) {
			$json['warn'] = L('resource.delete.noChoice');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] != '停用') {
					$warn = L('resource.delete.stateError');
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					//返回
					$warn = L('resource.delete.success');
					$x++;
				}
				$text .= str_replace(['{{id}}'], [$info['id']], L('resource.delete.text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('resource.delete.log')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('resource.delete.warn'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'品名',
                    'aliasName'=>'品名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'类型',
                    'aliasName'=>'类型',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格',
                    'aliasName'=>'规格',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'参考单价',
                    'aliasName'=>'参考单价(元)',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'编码',
                    'aliasName'=>'编码',
                ],
                [
                    'columnName'=>'品名',
                    'aliasName'=>'品名',
                ],
                [
                    'columnName'=>'类型',
                    'aliasName'=>'类型',
                ],
                [
                    'columnName'=>'规格',
                    'aliasName'=>'规格',
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',
                ],
                [
                    'columnName'=>'参考单价',
                    'aliasName'=>'参考单价',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }

}
